/// 存储用户信息到 key-value

import 'package:cloudapp/esdk/db.dart';
import 'package:cloudapp/esdk/esync.dart';
import 'package:cloudapp/esdk/model/server_info.dart';
import 'package:cloudapp/esdk/model/session_info.dart';

import 'response/user_login_response.dart';

const storageKey = "E-SYNC";

/// 启动时要进行的异步操作
Future<UserLoginResponse> initStorage() async {
  // 首先是数据库初始化
  await DbStorage.i().initDb();

  // 需要加载会话与服务器信息
  var sessionLists = await DbStorage.i().loadAllSessions();
  var serverLists = await DbStorage.i().loadAllServers();

  // 先排序 sessionLists 按 lastUsed 倒序
  sessionLists.sort((a, b) {
    return b.lastUsed.compareTo(b.lastUsed);
  });

  // 将serverLists 转为map
  var serverMaps = <int, ServerInfo>{};
  for(var server in serverLists) {
    serverMaps[server.id] = server;
  }

  // 找到第一个合适的
  SessionInfo result;
  ServerInfo server;
  var found = false;
  for(var session in sessionLists) {
    // 若此会话的服务器有效，且会话token信息有效
    if(serverMaps.containsKey(session.serverId) && session.loginResponse.isNotEmpty) {
      found = true;
      result = session;
      server = serverMaps[session.serverId];
    }
  }

  if(found) {
    ESync.i().setServerHost(server.inIpAddr);
    return result.userInfo;
  }

  return null;
}
